import sys
import os
import random
import configparser
import cx_Oracle
from PySide6 import QtCore
from PySide6.QtCore import Qt
from PySide6.QtCore import (QCoreApplication, QDate, QDateTime, QLocale,
    QMetaObject, QObject, QPoint, QRect,
    QSize, QTime, QUrl, Qt)
from PySide6.QtGui import (QBrush, QColor, QConicalGradient, QCursor,
    QFont, QFontDatabase, QGradient, QIcon,
    QImage, QKeySequence, QLinearGradient, QPainter,
    QPalette, QPixmap, QRadialGradient, QTransform)
from PySide6.QtWidgets import (QApplication, QLabel, QMainWindow, QMenuBar,
    QPushButton, QSizePolicy, QStatusBar, QTextEdit,
    QWidget, QVBoxLayout, QStyleFactory, QDialog, QFrame, 
    QHeaderView, QAbstractItemView, QTableWidgetItem, QCheckBox, QHBoxLayout,
    QFileDialog, QMessageBox)
from ui.ui_main import Ui_MainWindow
from ui.ui_dlg_choose_date import Ui_dlgChooseDate
from dlg_choose_date import DlgChooseDate
from report_tool import get_prd_list, get_value_table, generate_excel, read_excel, get_trade_by_type
import logging

logging.basicConfig(
    filename = os.path.join(os.path.join(os.getcwd(), 'logs'), 'lczg.log'),
    level = logging.DEBUG,
    format = "[%(asctime)s] - %(levelname)s - %(lineno)s] %(message)s",
    datefmt = "%Y-%m-%d %H:%M:%S"
)

class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.connect = None
        self.cur = None
        # 净值日期
        self.choose_date = None
        # 债券分类列表
        self.trade_list = None
        # 表格数据暂存
        self.rows = []
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.setWindowTitle("信托数据导出")
        # 选择净值按钮的行为
        self.ui.btnChoseDate.clicked.connect(self.chooseDate)
        # 关闭按钮行为
        self.ui.btnExit.clicked.connect(self.quitDlg)
        # 导出文件
        self.ui.btnExport.clicked.connect(self.exportData)
        # 导入债券分类
        self.ui.btnImportTrades.clicked.connect(self.importTrades)
        # 保存设置
        self.ui.btnSaveConfig.clicked.connect(self.saveConfig)
        # 加载配置文件
        self.loadConfig()

    def loadConfig(self):
        config_path = os.path.join(os.path.join(os.getcwd(), 'config'), 'lczg_prod.ini')
        config = configparser.ConfigParser()
        config.read(config_path, encoding='utf-8')
        DB_USERNAME = config['DB']['USER_NAME']
        DB_PASSWD = config['DB']['PASSWD']
        DB_CONNSTR = config['DB']['CONNSTR']
        LIBDIR = config['DB']['LIBDIR']
        self.ui.txtJDBC.setText(DB_CONNSTR)
        self.ui.txtUserName.setText(DB_USERNAME)
        self.ui.txtPasswd.setText(DB_PASSWD)
        self.ui.txtOracleHome.setText(LIBDIR)
        try:
            cx_Oracle.init_oracle_client(lib_dir=LIBDIR)
            self.connect = cx_Oracle.connect(DB_USERNAME, DB_PASSWD, DB_CONNSTR)
            self.cur = self.connect.cursor()
        except:
            logging.error('连接异常')
    
    def saveConfig(self):
        config_path = os.path.join(os.path.join(os.getcwd(), 'config'), 'lczg_prod.ini')
        jdbc = self.ui.txtJDBC.text()
        username = self.ui.txtUserName.text()
        passwd = self.ui.txtPasswd.text()
        oracleHome = self.ui.txtOracleHome.text()
        config = '''[DB]
    USER_NAME = {}
    PASSWD = {}
    CONNSTR = {}
    LIBDIR = {}
    '''.format(username, passwd, jdbc, oracleHome)
        logging.debug(config)
        with open(config_path, "w") as f:
            f.write(config)
        self.loadConfig()
        QMessageBox.warning(None, "温馨提示", "配置修改成功！", QMessageBox.Yes)
        self.ui.tabWidget.setCurrentIndex(0)
        

    
    def importTrades(self):
        self.trade_list = None
        file_path, _ = QFileDialog.getOpenFileName(self, "打开债券分类", os.getcwd() ,"Microsoft Excel 97-2003文件(*.xls);;Microsoft Excel文件(*.xlsx);;all files(*.*)")
        if file_path is None or file_path == '':
            return
        logging.info('file_path:{}'.format(file_path))
        self.trade_list = read_excel(file_path)
        logging.debug(self.trade_list)
        table = self.ui.tableWidgetTrades
        table.setRowCount(len(self.trade_list))
        table.setColumnCount(3)
        table.setHorizontalHeaderLabels(['债券代码','债券名称', '债券类型'])
        table.horizontalHeader().setFixedHeight(50)
        table.horizontalHeader().setStyleSheet('QHeaderView::section{background:#e4f6d4}')
        table.horizontalHeader().setSectionResizeMode(1, QHeaderView.Stretch)
        table.horizontalHeader().setStretchLastSection(True)
        table.setSelectionMode(QAbstractItemView.SingleSelection)
        table.setSelectionBehavior(QAbstractItemView.SelectRows)
        for i in range(len(self.trade_list)):
            trade = self.trade_list[i]
            table.setItem(i, 0, QTableWidgetItem(trade['trade_code']))
            table.setItem(i, 1, QTableWidgetItem(trade['trade_name']))
            table.setItem(i, 2, QTableWidgetItem(trade['trade_type']))
        QMessageBox.warning(None, "温馨提示", "导入债券分类成功！", QMessageBox.Yes)

    def chooseDate(self, date):
        dlgChooseDate = DlgChooseDate()
        dlgChooseDate.exec()
        choose_date = dlgChooseDate.getDate()
        logging.info('choose_date:{}'.format(choose_date))
        if not choose_date:
            return
        self.ui.labelDate.setText(choose_date)
        self.choose_date = choose_date
        self.query_list(choose_date)
    
    def quitDlg(self):
        sys.exit()

    # 查找产品列表
    def query_list(self, choose_date):
        data = get_prd_list(self.cur, choose_date)
        logging.debug(data)
        table = self.ui.tableWidget
        table.setRowCount(len(data))
        table.setColumnCount(5)
        table.setHorizontalHeaderLabels(['选择','账套代码','账套简称','净值日期','产品类型'])
        table.horizontalHeader().setFixedHeight(50)
        table.horizontalHeader().setStyleSheet('QHeaderView::section{background:#e4f6d4}')
        table.horizontalHeader().setSectionResizeMode(2, QHeaderView.Stretch)
        table.horizontalHeader().setStretchLastSection(True)
        table.setSelectionMode(QAbstractItemView.SingleSelection)
        table.setSelectionBehavior(QAbstractItemView.SelectRows)
        for i in range(len(data)):
            item = data[i]
            ck = QCheckBox()
            h = QHBoxLayout()
            h.setAlignment(Qt.AlignCenter)
            h.addWidget(ck)
            w = QWidget()
            w.setLayout(h)
            table.setCellWidget(i, 0, w)
            table.setItem(i, 1, QTableWidgetItem(item[1]))
            table.setItem(i, 2, QTableWidgetItem(item[2]))
            table.setItem(i, 3, QTableWidgetItem(item[0]))
            table.setItem(i, 4, QTableWidgetItem(item[3]))
            # 暂存所有产品
            self.rows.append([ck, item[1], item[2]])
    
    def exportData(self):
        # 检查是否已选择净值
        if self.choose_date is None:
            QMessageBox.warning(None, "温馨提示", "请先选择净值日期！", QMessageBox.Yes)
            return
        if self.trade_list is None:
            QMessageBox.warning(None, "温馨提示", "请先导入债券分类！", QMessageBox.Yes)
            return
        # 获取选中的产品
        prd_list = [(x[1], x[2]) for x in self.rows if x[0].isChecked()]
        logging.debug(prd_list)
        if len(prd_list) == 0:
            QMessageBox.warning(None, "温馨提示", "请勾选要导出的记录！", QMessageBox.Yes)
            return
        file_data = []
        for (prd_id, prd_name) in prd_list:
            # 计算每个产品的金额
            prd_values = get_value_table(self.cur, prd_id, self.choose_date, self.trade_list)
            file_data.append({
                'prod_id': prd_id,
                'prd_name': prd_name,
                'prod_values': prd_values
            })
        logging.info(file_data)
        file_path, _ =  QFileDialog.getSaveFileName(self,"保存", os.getcwd() ,"Microsoft Excel 97-2003文件(*.xls);;all files(*.*)")
        logging.info(file_path)
        if file_path is None or file_path == '':
            logging.info('取消导出')
            return
        logging.info(file_path)
        generate_excel(file_data, self.choose_date, file_path)
        QMessageBox.warning(None, "温馨提示", "导出成功！", QMessageBox.Yes)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    app.setStyle(QStyleFactory.create("Fusion"))
    window = MainWindow()
    window.setWindowFlags(QtCore.Qt.MSWindowsFixedSizeDialogHint)
    window.setWindowIcon(QIcon(os.path.join(os.path.join(os.getcwd(), "res"), "bird.png")))
    window.show()
    sys.exit(app.exec())
